package com.wiz.netty.handler;

import io.netty.channel.ChannelHandlerContext;

import java.net.InetSocketAddress;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.wiz.data.vo.type.MessageType;
import com.wiz.log.NettyInfoRecord;
import com.wiz.netty.NettyXmlParseFactory;
import com.wiz.netty.message.NettyMessageTO;
import com.wiz.netty.service.NettyLoginThread;
import com.wiz.netty.service.NettyThreadPool;
import com.wiz.web.manager.ServiceManager;

public class LoginHandler extends AbstractHandlerAdapter {
	private transient final Logger log = LoggerFactory.getLogger(getClass());
	
	public LoginHandler(ServiceManager serviceManager, NettyXmlParseFactory wizXmlFactory){
		super();
		this.serviceManager = serviceManager;
		this.wizXmlFactory = wizXmlFactory;
	}
	
	@Override
	public void channelRead(ChannelHandlerContext ctx,Object msg) throws Exception{
		NettyMessageTO.MessageContent message = (NettyMessageTO.MessageContent)msg;
		String stationId = message.getIden().toStringUtf8();
		if(message.getType() == MessageType.SIGN.getId()){
			//绑定站点号与连接
			if(!serviceManager.getStationConnectMap().containsKey(stationId)){
				InetSocketAddress client = (InetSocketAddress) ctx.channel().remoteAddress();
				String clientIp = client.getAddress().getHostAddress();
				if(clientIp.indexOf("0.0.0.0")>=0){
					NettyInfoRecord.warnRecord("stationId="+stationId+" channelId="+ctx.channel().id().asLongText()+" Exception");
					destroyHandler(ctx,"LoginHandler close");
					return;
				}
				NettyInfoRecord.infoRecord("stationId="+stationId+" channelId="+ctx.channel().id().asLongText()+" is  connecting");
				//下发动态密钥
				NettyThreadPool.proccess(new NettyLoginThread(ctx,message,serviceManager,wizXmlFactory));
				serviceManager.getStationConnectMap().put(stationId, ctx.channel());
				return;
			}else{
				destroyHandler(ctx,"LoginHandler.channelRead already contains station");
//				ctx.fireChannelRead(msg);
			}
		}else{
			//起到filter的作用
			if(serviceManager.getStationConnectMap().containsValue(ctx.channel())){//如果已经包含此站点号，代表已注册，消息合法
				ctx.fireChannelRead(msg);
			}else{//认为是非法数据,强迫此连接断开
				log.warn("this data="+message.toByteString()+" from invalid station:"+stationId);
				ctx.close();
			}
		}
	}
	
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
		NettyInfoRecord.errorRecord(cause.getMessage()+" in LoginHandler");
	}
}

